import {View} from '@tarojs/components'

import {AtButton, AtRadio} from "taro-ui";
import {useEffect, useState} from "react";
import Taro from "@tarojs/taro";
import './index.scss'
import GlobalFooter from "../../components/global-footer";
import questions from '../../data/question.json'

/**
 * 答题页面
 */
export default () => {
  // 当前题目索引
  const [currentIndex, setCurrentIndex] = useState<number>(1);
  // 当前题目
  const [currentQuestion, setCurrentQuestion] = useState(questions[currentIndex - 1]);
  // 题目选项
  let questionOptions = currentQuestion.options.map((options) => {
    return {label: `${options.key}.${options.value}`, value: options.key}
  });
  // 当前答案
  const [currentAnswer, setCurrentAnswer] = useState<string>();
  // 答案列表
  const [answerList] = useState<string[]>([])

  useEffect(() => {
    // 更新当前题目
    setCurrentQuestion(questions[currentIndex - 1])
    // 更新当前答案
    setCurrentAnswer(answerList[currentIndex - 1])
  }, [currentIndex]);

  return <View className='do-question'>
    <View className='at-article__h1 question-title'>
      {currentIndex}、{currentQuestion.title}
    </View>
    <AtRadio className='question-options'
             options={questionOptions}
             value={currentAnswer}
             onClick={(value) => {
               setCurrentAnswer(value);
               answerList[currentIndex - 1] = value;
             }}
    />
    <View className='button-group'>
      {currentIndex < questions.length && (
        <AtButton type={"primary"} className='control-btn' disabled={!currentAnswer} circle onClick={() => {
          setCurrentIndex(currentIndex + 1)
        }}
        >下一题</AtButton>)}

      {currentIndex === questions.length && (
        <AtButton type={"primary"} className='control-btn' disabled={!currentAnswer} circle onClick={() => {
          Taro.setStorageSync('answerList', answerList);
          Taro.reLaunch({
            url: '/pages/result/index'
          });
        }}
        >查看答案</AtButton>)}

      {currentIndex > 1 && (<AtButton className='control-btn' circle onClick={() => {
        setCurrentIndex(currentIndex - 1)
      }}
      >上一题</AtButton>)}
    </View>
    <GlobalFooter></GlobalFooter>
  </View>;
}

